package ru.ifmo.croak.impl.remoting.query.team3;

import ru.ifmo.croak.api.Message;
import ru.ifmo.croak.api.MessageListener;
import ru.ifmo.croak.api.MessageQuery;
import ru.ifmo.croak.api.QueryService;

import java.rmi.RemoteException;
import java.util.List;

public class ServerQueryImpl implements ServerQuery, MessageListener {
    private final QueryService service;
    private final RemoteMessageQuery remoteQuery;
    private final MessageQuery localQuery;

    public ServerQueryImpl(QueryService service, RemoteMessageQuery remoteQuery) throws RemoteException {
        this.service = service;
        this.remoteQuery = remoteQuery;

        localQuery = service.createQuery(remoteQuery.getRequest());
        localQuery.setMessageListener(this);
    }

    @Override
    public Message[] getMessages() throws RemoteException {
        return localQuery.getMessages().toArray(new Message[] {});
    }

    @Override
    public void close() throws RemoteException {
        localQuery.close();
    }

    @Override
    public void messageAvailable(Message message) {
        try {
            remoteQuery.messageAvailable(message);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
